#!/usr/bin/env python3
"""
跨平台自动打包脚本
支持Windows、macOS、Linux
"""

import os
import sys
import shutil
import subprocess
import platform
from pathlib import Path

class AutoBuilder:
    def __init__(self):
        self.system = platform.system().lower()
        self.scripts = {
            'liupai': {
                'script': 'liupai.py',
                'name': 'liupai-tiaozhan',
                'data': 'liupai'
            },
            'yiji': {
                'script': 'yiji_clicker.py', 
                'name': 'yiji-huodong',
                'data': 'yiji'
            }
        }
        
    def clean_build(self):
        """清理旧的构建文件"""
        dirs_to_clean = [
            'build', 
            'dist', 
            '__pycache__', 
            'auto-clicker-darwin',  # 清理发布包目录
            'auto-clicker-windows',
            'auto-clicker-linux'
        ]
        files_to_clean = [
            f for f in os.listdir() 
            if f.endswith('.spec') or f.startswith('auto-clicker-') and f.endswith(('.tar.gz', '.zip'))
        ]
        
        for dir_name in dirs_to_clean:
            if os.path.exists(dir_name):
                shutil.rmtree(dir_name)
                print(f"✅ 已清理 {dir_name}")
                
        for file_name in files_to_clean:
            if os.path.exists(file_name):
                os.remove(file_name)
                print(f"✅ 已清理 {file_name}")
    
    def get_pyinstaller_path(self):
        """获取pyinstaller路径"""
        try:
            result = subprocess.run(['pyinstaller', '--version'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                return 'pyinstaller'
        except FileNotFoundError:
            pass
            
        # 尝试使用python -m PyInstaller
        return [sys.executable, '-m', 'PyInstaller']
    
    def build_app(self, config):
        """构建单个应用"""
        pyinstaller = self.get_pyinstaller_path()
        if not pyinstaller:
            print("❌ 未找到PyInstaller，请先安装: pip install pyinstaller")
            return False
            
        script_path = config['script']
        app_name = config['name']
        data_path = config['data']
        
        # 根据系统设置数据路径分隔符
        separator = ';' if self.system == 'windows' else ':'
        
        if isinstance(pyinstaller, str):
            cmd = [pyinstaller]
        else:
            cmd = pyinstaller
            
        cmd.extend([
            '--onedir',  # 目录格式，启动更快
            '--clean',
            '--noconfirm',
            script_path,
            '--name', app_name,
            '--add-data', f'{data_path}{separator}{data_path}'
        ])
        
        # 添加隐藏导入
        cmd.extend(['--hidden-import', 'cv2'])
        cmd.extend(['--hidden-import', 'numpy'])
        cmd.extend(['--hidden-import', 'PIL'])
        cmd.extend(['--hidden-import', 'mss'])
        
        print(f"🚀 正在构建 {app_name}...")
        print(f"命令: {' '.join(cmd)}")
        
        try:
            result = subprocess.run(cmd, check=True)
            if result.returncode == 0:
                print(f"✅ {app_name} 构建成功!")
                return True
        except subprocess.CalledProcessError as e:
            print(f"❌ {app_name} 构建失败: {e}")
            return False
    
    def create_package(self):
        """创建发布包"""
        if not os.path.exists('dist'):
            print("❌ dist目录不存在，请先构建")
            return False
            
        # 为每个应用创建单独的压缩包
        for app_key, config in self.scripts.items():
            app_name = config['name']
            src_dir = Path('dist') / app_name
            
            if not src_dir.exists():
                print(f"⚠️  {app_name} 目录不存在，跳过")
                continue
            
            # 创建压缩包名称
            system_name = {
                'windows': 'windows',
                'darwin': 'macos', 
                'linux': 'linux'
            }.get(self.system, self.system)
            
            package_name = f"{app_name}-{system_name}"
            
            # 创建releases目录
            releases_dir = Path('releases')
            releases_dir.mkdir(exist_ok=True)
            
            # 统一使用zip格式（跨平台兼容）
            zip_path = releases_dir / package_name
            shutil.make_archive(str(zip_path), 'zip', 'dist', app_name)
            print(f"✅ 压缩包已创建: {zip_path}.zip")
            
        return True
    
    def run(self):
        """主运行函数"""
        # 处理命令行参数
        if len(sys.argv) > 1 and sys.argv[1] == '--clean':
            self.clean_build()
            print("✅ 清理完成!")
            return True
            
        print(f"🎯 开始构建 - 平台: {self.system}")
        
        # 清理（但保留虚拟环境）
        self.clean_build()
        
        # 检查依赖
        try:
            import cv2, numpy, PIL, pyautogui
            print("✅ 依赖检查通过")
        except ImportError as e:
            print(f"❌ 缺少依赖: {e}")
            print("请先安装: pip install -r requirements.txt")
            return False
        
        # 构建所有应用
        success = True
        for config in self.scripts.values():
            if not self.build_app(config):
                success = False
        
        if success:
            self.create_package()
            print("🎉 所有应用构建完成!")
        else:
            print("❌ 部分应用构建失败")
            
        return success

if __name__ == '__main__':
    builder = AutoBuilder()
    success = builder.run()
    sys.exit(0 if success else 1)